﻿using System.Modules.ExceptionHanlding;
using System.Xml;
using Microsoft.SharePoint;

namespace System.Modules.SharePoint.Extensions
{
    /// <summary>
    /// SP Field Lookup Extensions
    /// </summary>
    public static class SPFieldLookupExtensions
    {
        #region SetLookupList
        /// <summary>
        /// Use this method to Set Look up Field List Parameter Value.
        /// </summary>
        /// <param name="field"></param>
        /// <param name="list"></param>
        public static void SetLookupList(this SPFieldLookup field, SPList list)
        {
            #region Constants
            const string NODE_FIELD = "Field";
            const string NODE_LIST = "List";
            #endregion

            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(field.SchemaXml);
                XmlNode node = xmlDoc.SelectSingleNode(NODE_FIELD);
                if (node != null)
                {
                    if (node.Attributes != null)
                    {
                        XmlAttribute listAttribute = node.Attributes[NODE_LIST];
                        if (listAttribute != null)
                        {
                            listAttribute.Value = list.ID.ToString("B");
                            field.SchemaXml = xmlDoc.InnerXml;
                            field.LookupWebId = list.ParentWeb.ID;
                            field.Update(true);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                exception.Handle();
            }
        }
        #endregion
    }
}